﻿using System;
using System.IO;
using System.Net;
using FourSquare.Domain.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FourSquare.Core
{
    public class APIAccess
    {
        public string Uri { get; set; }

        public string PostAction()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);
            request.Method = "POST";
            request.PreAuthenticate = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C10 Safari/419.3";
            string returnData = "";

            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(returnData);
                    writer.Close();
                }
            }

            return "";
        }

        public string GetResponse()
        {
            WebRequest request = WebRequest.Create(Uri);
            WebResponse response = request.GetResponse();
            string result = "";
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }

            return result;
        }


        public Meta GetMetaResponse(string result)
        {
            JToken o = JToken.Parse(result);
            var metaResponse = o.SelectToken("meta");
            Meta meta = JsonConvert.DeserializeObject<Meta>(metaResponse.ToString());

            return meta;
        }
    }

}
